package red.lixiang.controller;

import red.lixiang.base.WXConfig;
import red.lixiang.model.BaseInfo;
import red.lixiang.model.Order;
import red.lixiang.model.Product;
import red.lixiang.model.WeChatInfo;
import red.lixiang.service.OrderService;
import red.lixiang.service.ProductService;
import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static red.lixiang.base.APPCONST.WECHAT_INFO;
import static red.lixiang.base.APPCONST.appID;

@Controller
public class PayController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/pay/weChatPay")
    @ResponseBody
    public String weChatPay(@RequestParam(required = false) Integer orderId,
                            @RequestParam(required = false) String address,
                            HttpServletRequest request){
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);

        Order orderTemp = new Order();
        orderTemp.setOrderId(orderId);
        orderTemp.setAddressId(address);
        orderService.updateOrder(orderTemp);

        //开始检查库存
        Map<String ,Object> orderMap = (Map<String, Object>) orderService.getOrderById(orderId).getObject();
        List<Product> productList = (List<Product>) orderMap.get("products");
        for (Product product : productList) {
            Product product1 = (Product) productService.getProductByBarCode(product.getBarCode()).getObject();
            if(!(product1.getProductNum()>0)){
                //如果没有库存
                String message = "对不起，您所选的"+product1.getProductName()+" "+product1.getColorName()+" "
                        +product1.getSizeName()+"已被别人抢先买啦，请返回购物车刷新！";
                BaseInfo baseInfo =new BaseInfo("100",message);
                return JSON.toJSONString(baseInfo);

            }
        }


        //初始化支付账户
        WXConfig config = new WXConfig();
        WXPay wxpay = new WXPay(config);

        Order order = (Order) orderMap.get("orderInfo");
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "德蒙斯特线上商城-童装");
        data.put("out_trade_no", String.valueOf(order.getOrderId()));
        data.put("device_info", "WEB");
        data.put("fee_type", "CNY");
        data.put("total_fee", String.valueOf((order.getTotalPrice().intValue()*100)));
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://www.example.com/wxpay/notify");
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
//        data.put("product_id", String.valueOf(order.getOrderId()));
        data.put("openid", weChatInfo.getOpenid());

        SortedMap<String , String > returnMap = new TreeMap<>();

        try {
            Map<String ,String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            data.putAll(resp);
            String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
            returnMap.put("appId",appID);
            returnMap.put("timeStamp",timeStamp);
            returnMap.put("nonceStr",resp.get("nonce_str"));
            returnMap.put("package","prepay_id="+resp.get("prepay_id"));
            returnMap.put("signType","MD5");
            String sign = WXPayUtil.generateSignature(returnMap,"qwertyuiopasdfghjklxcvbnmgcvbjkf");
            returnMap.put("paySign",sign);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSON.toJSONString(returnMap);
    }
}
